<!--
 * @Description: 资源管理---运维资源---数据目录
 * @Author: 魏勇
 * @Date: 2020-03-09 15:36:26
 * @LastEditTime: 2020-03-31 18:16:32
 * @LastEditors: 魏勇
 -->
<template>
    <el-row ref="tableRowEl" class="dyTable">
        <el-table
                ref="tableObj"
                :data="tableData"
                :max-height="maxHeight"
                :height="tableHeight"
                size="small"
                tooltip-effect="dark"
                highlight-current-row
                header-row-class-name="header-row"
                @select="(selection, row) => handleRowClick(row)"
                @row-click="handleRowClick"
                style="width: 100%">

            <el-table-column type="selection">
            </el-table-column>

            <el-table-column v-if="orderNum"
                    type="index"
                    label="序号"
                    width="70">
            </el-table-column>

            <el-table-column :sortable="item.sortable" :key="index" v-for="(item,index) in cols" :prop="item.id" :label="item.label"  v-if="item.gridShow!==false"
                             :width="item.width">
                <template slot-scope="scope">
                    <span  v-if="item.editorType==='selectDrop'" style="margin-left:2px">{{ item["cellFun"]!=null?item["cellFun"](scope.row,item.id):item.optionsMap&&scope.row[item.id]&&item.optionsMap[scope.row[item.id]+""] }}</span>

                    <app-status v-else-if="item.editorType==='stateSelect'"
                                :type="item.getState&&item.getState(scope.row[item.id])"
                                :text="item.getLabel&&item.getLabel(scope.row[item.id])"></app-status>
                    <div :title='item["cellFun"]!=null?item["cellFun"](scope.row):scope.row&&scope.row[item.id]' :class="item.extendClass||''"  v-else style="margin-left: 2px">{{ item["cellFun"]!=null?item["cellFun"](scope.row):scope.row&&scope.row[item.id] }}</div>

                </template>
            </el-table-column>
<!--操作栏-->
            <el-table-column
                    v-if="this.operations.length>0"
                    fixed="right"
                    label="操作"
                    :width="operationWid">
                <template slot-scope="scope">
                    <el-button  :disabled="(btnItem.getDisable&&btnItem.getDisable(btnItem.id,scope.row))||false" :key="btnItem.id" v-for="(btnItem,index) in operations" @click.stop="handleClick(scope.row,btnItem.id)" type="text" size="small">{{btnItem.label}}</el-button>
                </template>
            </el-table-column>

        </el-table>
        <!--        分页条-->
        <el-row class="table_page_bar" >
            <el-pagination
                    style="float: right"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="totalPageSizes"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </el-row>

    </el-row>

</template>

<script>
    import AppStatus from "@/components/AppCommon/AppStatus"
    import {totalPageSize, totalPageSizes} from "../../../utils/tool";
    import { Loading } from 'element-ui';

    export default {
        name: "el-table-ctl",
        components: {
            AppStatus
        },
        props: {
            dynamic:{type: Boolean, default: false},//多router-view嵌套下 需要设置该属性
            //数据集合
            datas: Array, default: () => {
                return []
            },
            //查询参数
            params: {
                type: Object, default: () => {
                    return {}
                }
            },
            fixOperation: {type: Boolean, default: false},//固定操作栏的高度 只是动态表格需要该属性
            height: {type: Number, default: 100},
            queryLoading: {type: Boolean, default: true},
            operationWid: {type: Number, default: 140},
            maxHeight: {type: Number, default: 400},
            orderNum: {type: Boolean, default: true},
            selectBox: {type: Boolean, default: true},
            moreSel: {type: Boolean, default: false},
            cols: {
                type: Array, default: () => {
                    return []
                }
            },
            operations: {
                type: Array, default: () => {
                    return []
                }
            }
        },
        computed: {},
        data:function(){
            return {
                selRows:{},
                tableHeight:this.maxHeight,
                queryParams:{},//查询参数
                totalPageSizes:totalPageSizes,
                paramsObj:null,
                urlName:null,
                pageSize:totalPageSize,
                idKey: "id",
                selRowIds: [],
                currentPage: 1,
                loadingInstance:null,
                total: 0,
                dataTimer:300,
                headerHeight:39,//表头的高度
                curRowId: "",
                tableData: this.datas||[]
            }
        },
        created() {

        },
        mounted() {
        },
        watch: {
            datas(newVal){
                this.tableData=newVal;
            }
        },
        methods: {
            //获取当前行 根据id
            getCurRowById(curSelId){
                return this.selRows[curSelId];
            },
            //设置其中的查询参数
            setQueryParams(params){
                this.queryParams=params;
            },
            addRow(json){
                this.tableData.push(json);
            },
            //处理行切换事件
            handleSelectionChange(data) {

                this.selRowIds=[];
                data.forEach((itemObj)=>{
                    this.selRowIds.push(itemObj["id"]);
                    this.selRows[itemObj["id"]]=itemObj;
                    this.$refs.tableObj.toggleRowSelection(itemObj, false);
                });
            },
            //点击操作里面的按钮事件
            handleClick(row,itemId){
               this.$emit('operationClick',{row,id:itemId})
            },
            //初始化表格高度
            initHeight(){
                //如果是动态表格才需要如此操作 因为表格组件存在bug 需要通过该方法来纠正 多router-view导致的高度计算异常
                if(this.dynamic){
                    setTimeout(()=>{
                        if(this.$refs.tableRowEl==null){
                            return void(0);
                        }
                        if(this.$refs.tableRowEl.$el==null){
                            return void(0);
                        }
                        this.tableHeight=this.maxHeight;
                        let oldHeight=this.$refs.tableRowEl.$el.querySelector(".el-table__body-wrapper").style.height;
                        if(parseFloat(oldHeight)!=this.maxHeight){
                            this.$refs.tableRowEl.$el.querySelector(".el-table__body-wrapper").style.height=(parseFloat(this.maxHeight)-this.headerHeight)+"px";
                        }
                        if(this.fixOperation){
                            this.$refs.tableRowEl.$el.querySelector(".el-table__fixed-body-wrapper").style.top=this.headerHeight+"px";
                        }
                        this.loadingInstance.close();
                    },this.dataTimer);
                }
            },
            //刷新表格的事件
            flushGridByUrl(urlName,paramsObj={method: 'POST'},tempParams={},backFun){
                this.paramsObj=paramsObj;
                this.urlName=urlName;
                //如果是post方式提交
                if(this.queryLoading){
                    this.loadingInstance = Loading.service({text:"加载中"});
                }
                if(paramsObj["method"]==="POST"){
                    this.api[urlName]({...this.params,...tempParams,...this.queryParams,pageNum:this.currentPage,pageSize:this.pageSize},{loading:false})
                        .then(res => {
                            this.initHeight();
                            //关闭提示
                            if(this.queryLoading&&!this.dynamic){
                                this.loadingInstance.close();
                            }
                            this.tableData=[];
                            this.selRowIds=[];
                            this.curRowId="";
                            this.total=parseInt(res.data["total"]||res.data["totalCount"]||0);
                            if(paramsObj&&paramsObj["dataFun"]){
                                if(res.data["list"]!=null){
                                    this.tableData=paramsObj["dataFun"](res.data["list"]);
                                }
                                if(res.data["records"]!=null){
                                    this.tableData=paramsObj["dataFun"](res.data["list"]);
                                }
                            }else{
                                if(res.data["list"]!=null){
                                    this.tableData=res.data["list"];
                                }
                                if(res.data["records"]!=null){
                                    this.tableData=res.data["records"];
                                }
                            }
                        })
                        .catch(err => {
                            console.warn(err.msg);
                            this.loadingInstance.close();
                        });
                }else{
                    //如果是get方式提交
                    this.params["pageNum"]=this.currentPage;
                    this.params["pageSize"]=this.pageSize;
                    this.api[urlName]({params: {...this.params,...tempParams,...this.queryParams} },{method: "get", customRequest: true})
                        .then(res => {
                            this.initHeight();
                            //关闭提示
                            if(this.queryLoading&&!this.dynamic){
                                this.loadingInstance.close();
                            }
                            this.tableData=[];
                            this.selRowIds=[];
                            this.curRowId="";
                            this.total=parseInt(res.data["total"]||0);
                            if(paramsObj&&paramsObj["dataFun"]){
                                this.tableData=paramsObj["dataFun"](res.data["list"]);
                            }else{
                                this.tableData=res.data["list"];
                            }
                        })
                        .catch(err => {
                            console.warn(err.msg);
                            this.loadingInstance.close();
                        });
                }

            },
            initPagin(){
                this.currentPage=1;
            },
            //刷新表格
            reloadData(backFun,extendParams={},initPage=false){
                if(initPage){
                    this.currentPage=1;
                }
                this.flushGridByUrl(this.urlName,this.paramsObj,extendParams,backFun);
            },
            //处理页的size变化
            handleSizeChange(size) {
                this.pageSize=size;
                this.flushGridByUrl(this.urlName,this.paramsObj);
            },
            //处理当前页变化
            handleCurrentChange(num) {
                this.currentPage=num;
                this.flushGridByUrl(this.urlName,this.paramsObj);
            },
            //选择记录checkBox
            selectRow(selection, row) {
                this.selRowIds=[];
                selection.forEach((itemObj)=>{
                    this.selRowIds.push(itemObj["id"]);
                });
            },
            //获取行id
            getRowId() {
               if(this.curRowId==null||this.curRowId===""){
                   return this.selRowIds.join(";");
               }
                return this.curRowId;
            },
            getRowIds() {
                return this.selRowIds.join(";");
            },
            //行点击事件
            handleRowClick(row, event, column) {
                if (!this.moreSel) {
                    this.$refs.tableObj.clearSelection();
                    this.selRowIds = [];
                }
                this.selRowIds = [];
                if (this.curRowId === row["id"]) {
                    this.curRowId = "";
                    this.$refs.tableObj.setCurrentRow();
                } else {
                    this.curRowId = row["id"];
                    this.selRowIds.push(this.curRowId);
                    this.$refs.tableObj.toggleRowSelection(row, true);
                }
                this.$emit("rowClick",{row})
            }
        },
        beforeDestroy(){
            this.loadingInstance=null;
        }
    };
</script>
